package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//全局异常处理器
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //统一处理字段重复
    //注意的是异常包:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
    @ExceptionHandler(DuplicateKeyException.class)//声明当前方法处理哪种异常
    public ResultInfo duplicateKeyExceptionHandler(Exception e) {
        e.printStackTrace();//打印
        return ResultInfo.error("名称重复");//返回结果
    }

    //业务异常
    @ExceptionHandler(CustomException.class)
    public ResultInfo customExceptionHandler(Exception e) {
        e.printStackTrace();//打印
        return ResultInfo.error(e.getMessage());//返回结果
    }

    //非预期异常
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionHandler(Exception e) {
        e.printStackTrace();//打印
        return ResultInfo.error("服务器开小差了,请稍后重试");//返回结果
    }
}